﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Data.OleDb;
using System.Threading;

namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }

        private SqlConnection conn = new SqlConnection();
        private const string namechcol = "Флаг";
        private Guid guid;
        private DataTable begdata = new DataTable();
        private DataTable city = new DataTable();
        private DataTable suppl = new DataTable();
        private DataTable anprice = new DataTable();
        private DataTable need = new DataTable();
        private DataTable order = new DataTable();
        private delegate void Deleg(object sender, EventArgs e);
        private Deleg del;
        private const string formtext = "Акции N + M";

        private struct OwnerDrugsCount 
        { 
            public string owner; 
            public int drugcode; 
            public int count;
            public int pharm;
            public string pharmname;
            public int order;
            public int rating;
            public string drugname;
            public OwnerDrugsCount(string owner, int drugcode, int count, int pharm, int order, int rating, string pharmname, string drugname)
            {
                this.count = count;
                this.drugcode = drugcode;
                this.owner = owner;
                this.pharm = pharm;
                this.rating = rating;
                this.order = order;
                this.pharmname = pharmname;
                this.drugname = drugname;
            }
        }

        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            conn.ConnectionString = @"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True";
            button1.Enabled = true;
            button5.Enabled = true;

            city.Load(ProcSel(conn, @"pas_CitySel"));
            foreach (DataColumn dc in city.Columns)
            {
                if (dc.ColumnName != "Флаг") dc.ReadOnly = true;
                else dc.ReadOnly = false;
            }
            suppl.Load(ProcSel(conn, @"pas_SupplSel"));
            foreach (DataColumn dc in suppl.Columns)
            {
                if (dc.ColumnName != "Флаг") dc.ReadOnly = true;
                else dc.ReadOnly = false;
            }
            guid = Guid.NewGuid();
            dataGridView1.DataSource = begdata.DefaultView;
            dataGridView2.DataSource = anprice.DefaultView;
            dateTimePicker1.Value = DateTime.Now.Date.AddDays(-1);
            dateTimePicker2.Value = DateTime.Now.Date.AddDays(-1);
        }



        private void button4_Click(object sender, EventArgs e)
        {
            if (conn.State == ConnectionState.Closed) conn.Open();
/*
            try
            {
                SqlCommand myCommand = conn.CreateCommand();
                myCommand.CommandType = CommandType.StoredProcedure;
                myCommand.CommandText = @"pas_GuidNatureCodeINS";
                myCommand.Parameters.Add("@guid", SqlDbType.UniqueIdentifier);
                myCommand.Parameters.Add("@code", SqlDbType.Int);
                myCommand.Parameters.Add("@del", SqlDbType.Bit);
                myCommand.Parameters.Add("@nature", SqlDbType.VarChar, 5);

                if (conn.State == ConnectionState.Closed) conn.Open();

                myCommand.Parameters["@guid"].Value = guid;
                myCommand.Parameters["@code"].Value = null;
                myCommand.Parameters["@del"].Value = true;
                myCommand.Parameters["@nature"].Value = null;
                myCommand.ExecuteNonQuery();

                guid = Guid.NewGuid();

                        //foreach (DataRow dr in dt_drug_tmp.Rows)
                        //    if (Convert.ToBoolean(dr[namechcol]) == true)
                        //    {
                        //        myCommand.Parameters["@guid"].Value = guid;
                        //        myCommand.Parameters["@code"].Value = Convert.ToInt32(dr["Код"]); ;
                        //        myCommand.Parameters["@del"].Value = false;
                        //        myCommand.Parameters["@nature"].Value = "drug";
                        //        myCommand.ExecuteNonQuery();
                        //    }            

                DataTable dt_rep = new DataTable();
 //               dt_rep.Load(RepProc(guid, conn, dateTimePicker1, dateTimePicker2, dateTimePicker3, dateTimePicker4, dateTimePicker5, dateTimePicker6, dateTimePicker7));
 //               dataGridView1.DataSource = dt_rep.DefaultView;

                myCommand.Parameters["@guid"].Value = guid;
                myCommand.Parameters["@code"].Value = null;
                myCommand.Parameters["@del"].Value = true;
                myCommand.Parameters["@nature"].Value = null;
                myCommand.ExecuteNonQuery();

                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                conn.Close();
            }*/
        }

        private SqlDataReader RepProc(int step,Guid id, SqlConnection sqlcon,int cdays,float lim,DateTimePicker dtp1,DateTimePicker dtp2)
        {
            SqlCommand sqlcom = sqlcon.CreateCommand();
            sqlcom.CommandType = CommandType.StoredProcedure;
            sqlcom.CommandText = @"pas_NplusM";
            sqlcom.CommandTimeout = 600;

            sqlcom.Parameters.Add("@step", SqlDbType.Int);
            sqlcom.Parameters["@step"].Value = step;

            sqlcom.Parameters.Add("@guid", SqlDbType.UniqueIdentifier);
            sqlcom.Parameters["@guid"].Value = id;

            sqlcom.Parameters.Add("@countdays", SqlDbType.Int);
            sqlcom.Parameters["@countdays"].Value = cdays;

            sqlcom.Parameters.Add("@limit", SqlDbType.Float);
            sqlcom.Parameters["@limit"].Value = lim;

            sqlcom.Parameters.Add("@datebeg", SqlDbType.Date);
            sqlcom.Parameters["@datebeg"].Value = dtp1.Value;

            sqlcom.Parameters.Add("@dateend", SqlDbType.Date);
            sqlcom.Parameters["@dateend"].Value = dtp2.Value;

            return sqlcom.ExecuteReader();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                DataGridView dgv = new DataGridView();
                if (tabControl1.TabPages.IndexOf(tabControl1.SelectedTab) == 0)
                    dgv = dataGridView1;
                if (tabControl1.TabPages.IndexOf(tabControl1.SelectedTab) == 1)
                    dgv = dataGridView2;
                if (tabControl1.TabPages.IndexOf(tabControl1.SelectedTab) == 2)
                    dgv = dataGridView3;
                if (tabControl1.TabPages.IndexOf(tabControl1.SelectedTab) == 3)
                    dgv = dataGridView4;
                if (dgv.DataSource != null && dgv.RowCount > 0)
                {
                    sfd.FileName = "N+M";
                    sfd.Filter = "Файл CSV | *.csv";
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        SaveDGVToCSVfile(sfd.FileName.ToString(), dgv, true);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public static bool SaveDGVToCSVfile(string filename, DataGridView table, bool openInExcel)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename, false, Encoding.Unicode);

                List<int> col_n = new List<int>();
                foreach (DataGridViewColumn col in table.Columns)
                    if (col.Visible)
                    {
                        sw.Write(col.HeaderText + "\t");
                        col_n.Add(col.Index);
                    }
                sw.WriteLine();
                int x = table.RowCount;
                if (table.AllowUserToAddRows) x--;

                for (int i = 0; i < x; i++)
                {
                    for (int y = 0; y < col_n.Count; y++)
                        sw.Write(table[col_n[y], i].Value + "\t");
                    sw.Write(" \r\n");
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            if (openInExcel)
            {
                try
                {
                    Process newProc = Process.Start("excel.exe", "\"" + filename + "\"");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            return true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            opf.Filter = "Файлы Excel (1997-2007)|*.XLSX;*.XLS";
            if (opf.ShowDialog() == DialogResult.OK)
            {

                try
                {
                    string filename = opf.FileName;
                    string ConStr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}; Extended Properties=Excel 8.0;", filename);
                    DataSet ds = new DataSet("EXCEL");
                    OleDbConnection cn = new OleDbConnection(ConStr);

                    if (cn.State == ConnectionState.Closed) cn.Open();
                    DataTable schemaTable = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { }); //{ null, null, null, null }
                    string sheet1 = (string)schemaTable.Rows[0].ItemArray[2];
                    string select = String.Format("SELECT * FROM [{0}]", sheet1);
                    OleDbDataAdapter ad = new OleDbDataAdapter(select, cn);
                    ad.Fill(ds);
                    begdata = ds.Tables[0];
                    if(begdata.Columns.Count > 0)
                    {
                        DataColumn flag = begdata.Columns.Add("Флаг",typeof(Boolean));
                        flag.ReadOnly = false;
                        begdata.Columns["Флаг"].SetOrdinal(0);
                        foreach (DataRow dr in begdata.Rows)
                        {
                            dr[0] = true;
                            dr[2] = dr[2].ToString().Replace(" ", "");
                        }
                        foreach (DataColumn dc in begdata.Columns)
                        {
                            if(dc.Ordinal != 0) dc.ReadOnly = true;
                        }
                        cn.Close();
                        DragDropDGV1();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            if (begdata.Rows.Count > 0) textBox3.Text = opf.FileName;
            else textBox3.Text = "не выбран";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            int fl = 0;
            string name = "";
            while (fl == 0)
            {
                city = FiltFormShow("Города", namechcol, "Город", city);
                fl = 0;
                foreach (DataRow dr in city.Rows)
                {
                    if (Convert.ToBoolean(dr["Флаг"]))
                    {
                        fl++;
                        name = Convert.ToString(dr["Город"]);
                    }
                }
                if (fl > 1)
                {
                    MessageBox.Show("Выбрано более одного города");
                    fl = 0;
                }
                else
                    if (fl == 0)
                        MessageBox.Show("Выберите поставщика");
            }
            if (fl == 1) textBox4.Text = name;
            else textBox4.Text = "не выбрано";

        }

        private SqlDataReader ProcSel(SqlConnection con,string procname)
        {
            SqlCommand com = con.CreateCommand();
            com.CommandType = CommandType.StoredProcedure;
            com.CommandText = procname;
            if (con.State == ConnectionState.Closed) con.Open();
            return com.ExecuteReader();
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            int fl = 0;
            string name = "";
            while (fl == 0)
            {
                suppl = FiltFormShow("Поставщики", namechcol, "Поставщик", suppl);
                fl = 0;
                foreach (DataRow dr in suppl.Rows)
                {
                    if (Convert.ToBoolean(dr["Флаг"]))
                    {
                        fl++;
                        name = Convert.ToString(dr["Поставщик"]);
                    }
                }
                if (fl > 1)
                {
                    MessageBox.Show("Выбрано более одного поставщика");
                    fl = 0;
                }
                else
                    if (fl == 0)
                        MessageBox.Show("Выберите поставщика");
            }
            if (fl == 1) textBox5.Text = name;
            else textBox5.Text = "не выбрано";
        }

        public DataTable FiltFormShow(string formname, string flname, string sort, DataTable dt)
        {
            PharmFilter.PharmFilter f = new PharmFilter.PharmFilter();
            f.Name = formname;
            f.dataGridView1.DataSource = dt.DefaultView;
            f.namechcol = flname;
            f.sortcoumn = sort;
            f.ShowDialog();
            f.Close();
            f = null;
            return dt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (tabControl1.TabPages.IndexOf(tabControl1.SelectedTab) == 0)
            {
                try
                {
                    dataGridView2.DataSource = null;
                    dataGridView3.DataSource = null;
                    dataGridView4.DataSource = null;
                    if (anprice != null) anprice.Clear();
                    need = null;
                    order = null;
                    del = new Deleg(AnPrice);
                    IAsyncResult asyncRes = del.BeginInvoke(sender, e, new AsyncCallback(CallBackFunc), null); //
                    Text += " Формируется таблица \"Анализ цен\"";
                    tabControl1.Enabled = false;
                    panel1.Enabled = false;
                    panel2.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ошибка при получении прайса\n" + ex.ToString());
                }
            }
            if (tabControl1.TabPages.IndexOf(tabControl1.SelectedTab) == 1)
            {
                try
                {
                    dataGridView3.DataSource = null;
                    dataGridView4.DataSource = null;
                    if (need != null) need.Clear();
                    order = null;
                    del = new Deleg(Need);
                    IAsyncResult asyncRes = del.BeginInvoke(sender, e, new AsyncCallback(CallBackFuncNeed), null); //
                    Text += " Формируется таблица \"Потребность\"";
                    tabControl1.Enabled = false;
                    panel1.Enabled = false;
                    panel2.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ошибка при расчете потребности\n" + ex.ToString());
                }
            }
            if (tabControl1.TabPages.IndexOf(tabControl1.SelectedTab) == 2)
            {
                try
                {
                    dataGridView4.DataSource = null;
                    if (order != null) order.Clear();
                    del = new Deleg(Order);
                    IAsyncResult asyncRes = del.BeginInvoke(sender, e, new AsyncCallback(CallBackFuncOrder), null); //
                    Text += " Формируется таблица \"Заказ\"";
                    tabControl1.Enabled = false;
                    panel1.Enabled = false;
                    panel2.Enabled = false;
                }                           
                catch (Exception ex)
                {
                    MessageBox.Show("Ошибка при расчете заказа \n" + ex.ToString());
                }
            }
        }

        private bool ProcIns(SqlConnection con,Guid g,int code,bool del,string nature,string natcomm)
        {
            try
            {
                SqlCommand myCommand = conn.CreateCommand();
                myCommand.CommandType = CommandType.StoredProcedure;
                myCommand.CommandText = @"pas_GuidNatureCodeINS";
                myCommand.Parameters.Add("@guid", SqlDbType.UniqueIdentifier);
                myCommand.Parameters.Add("@code", SqlDbType.Int);
                myCommand.Parameters.Add("@del", SqlDbType.Bit);
                myCommand.Parameters.Add("@nature", SqlDbType.VarChar, 5);
                myCommand.Parameters.Add("@naturecomm", SqlDbType.VarChar, 50);

                myCommand.Parameters["@guid"].Value = g;
                myCommand.Parameters["@code"].Value = code;
                myCommand.Parameters["@del"].Value = del;
                myCommand.Parameters["@nature"].Value = nature;
                myCommand.Parameters["@naturecomm"].Value = natcomm;
                if (con.State == ConnectionState.Closed) con.Open();
                myCommand.ExecuteNonQuery();
                myCommand = null;
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }
        }

        private void AnPrice(object sender,EventArgs e)
        {
            bool fl = false;
            guid = Guid.NewGuid();
            ProcIns(conn, guid, 0, true, "", "");

            CheckParam(sender, e);

            foreach (DataRow dr in begdata.Rows)
            {
                if (Convert.ToBoolean(dr[namechcol]) == true)
                {
                    fl = true;
                    ProcIns(conn, guid, 0, false, "supdr", dr[1].ToString());
                }
            }
            foreach (DataRow dr in suppl.Rows)
            {
                if (Convert.ToBoolean(dr[namechcol]) == true)
                {
                    ProcIns(conn, guid, Convert.ToInt32(dr[1]), false, "suppl", dr[1].ToString());
                }
            }
            foreach (DataRow dr in city.Rows)
            {
                if (Convert.ToBoolean(dr[namechcol]) == true)
                {
                    ProcIns(conn, guid, Convert.ToInt32(dr[1]), false, "city", dr[1].ToString());

                }
            }
            if (fl)
            {
                anprice.Clear();
                anprice = null;
                anprice = new DataTable();
                anprice.Load(RepProc(1, guid, conn, 4,Convert.ToSingle(2.5), dateTimePicker1, dateTimePicker2));
                anprice = AnPriceAddCol(anprice, begdata);
                anprice.Columns.Add("Отклонение,%", typeof(float));
                foreach (DataRow dr in anprice.Rows)
                {
                    dr["Отклонение,%"] = 100 * (Math.Round(Convert.ToSingle(dr["Мин цена"]) / Convert.ToSingle(dr["Цена"]),4) - 1);
                    if (Convert.ToSingle(dr["Отклонение,%"]) <= Convert.ToSingle(textBox2.Text)) dr["Флаг"] = false;
                    if (dr["Кредит-нота"] == DBNull.Value) dr["Кредит-нота"] = 0;
                }
                anprice.Columns["Флаг"].SetOrdinal(0);
                anprice.Columns["Код от поставщика"].SetOrdinal(1);
                anprice.Columns["Акция"].SetOrdinal(2);
                anprice.Columns["Кредит-нота"].SetOrdinal(3);
                anprice.Columns["Цена"].SetOrdinal(4);
                anprice.Columns["Код товара"].SetOrdinal(5);
                anprice.Columns["Товар"].SetOrdinal(6);
                anprice.Columns["Мин цена"].SetOrdinal(7);
                anprice.Columns["Отклонение,%"].SetOrdinal(8);

            }
            else MessageBox.Show("Не выбрано ни одной позиции");
            ProcIns(conn, guid, 0, true, "", "");
        }

        private void Need(object sender, EventArgs e)
        {
            bool fl = false;
            guid = Guid.NewGuid();
            ProcIns(conn, guid, 0, true, "", "");

            CheckParam(sender, e);

            foreach (DataRow dr in anprice.Rows)
            {
                if (Convert.ToBoolean(dr[namechcol]) == true)
                {
                    fl = true;
                    ProcIns(conn, guid, Convert.ToInt32(dr["Код товара"]), false, "drug", dr["Код товара"].ToString());
                }
            }
            foreach (DataRow dr in suppl.Rows)
            {
                if (Convert.ToBoolean(dr[namechcol]) == true)
                {
                    ProcIns(conn, guid, Convert.ToInt32(dr[1]), false, "suppl", dr[1].ToString());
                }
            }
            foreach (DataRow dr in city.Rows)
            {
                if (Convert.ToBoolean(dr[namechcol]) == true)
                {
                    ProcIns(conn, guid, Convert.ToInt32(dr[1]), false, "city", dr[1].ToString());

                }
            }
            if (fl)
            {
                if (need != null) need.Clear();
                need = null;
                need = new DataTable();
                need.Load(RepProc(2, guid, conn, 4, Convert.ToSingle(2.5), dateTimePicker1, dateTimePicker2));
                need.Columns.Remove("Дефектура");
                need.Columns.Add("Флаг", typeof(bool));
                foreach (DataRow dr in need.Rows)
                {
                    if (Convert.ToSingle(dr["Потребность"]) > 0) dr["Флаг"] = true;
                    else dr["Флаг"] = false;
                }
            }
            else MessageBox.Show("Не выбрано ни одной позиции");
            ProcIns(conn, guid, 0, true, "", "");
        }

        private void Order(object sender, EventArgs e)
        {
            if (dataGridView3.DataSource != null && dataGridView3.RowCount > 0 && dataGridView2.DataSource != null && dataGridView2.RowCount > 0)
            {
                OwnerDrugsCount[] odc = new OwnerDrugsCount[] {};
                OwnerDrugsCount[] odc_new = new OwnerDrugsCount[] { };
                if(order != null) order = null;
                order = new DataTable();
                order.Columns.Add("Код Аптека Ладушка", typeof(int));
                order.Columns.Add("Код поставщика", typeof(string));
                order.Columns.Add("Товар", typeof(string));
                order.Columns.Add("Аптека", typeof(string));
                order.Columns.Add("Юр лицо", typeof(string));      
                order.Columns.Add("Заказ", typeof(int));
                order.Columns.Add("Цена", typeof(float));
                order.Columns.Add("Сумма заказа", typeof(float));
                order.Columns.Add("Сумма бонуса", typeof(float));
                foreach (DataRow dr in need.Rows)
                {
                    if (Convert.ToBoolean(dr["Флаг"]))
                    {
                        bool flag = false;
                        for (int i = 0; i < odc.Length; i++)
                        {
                            if (odc[i].owner == Convert.ToString(dr["Юр лицо"]) && odc[i].drugcode == Convert.ToInt32(dr["Код товара"]))
                            {
                                flag = true;
                                odc[i].count += Convert.ToInt32(dr["Потребность"]);
                            }
                        }
                        if (!flag)
                        {
                            Array.Resize(ref odc, odc.Length + 1);
                            odc[odc.Length - 1].count = Convert.ToInt32(dr["Потребность"]);
                            odc[odc.Length - 1].drugcode = Convert.ToInt32(dr["Код товара"]);
                            odc[odc.Length - 1].owner = Convert.ToString(dr["Юр лицо"]);
                        }
                    }
                }

                for (int i = 0; i < odc.Length; i++)
                {
                    foreach (DataRow dr in anprice.Rows)
                    {
                        if (Convert.ToBoolean(dr["Флаг"]) && Convert.ToInt32(dr["Код товара"]) == odc[i].drugcode)
                        {
                            int cnt = Convert.ToInt32(Convert.ToString(dr["Акция"]).Substring(0, Convert.ToString(dr["Акция"]).IndexOf('+')));
                            if (cnt != 0 && cnt != 1)
                                odc[i].count = odc[i].count - (odc[i].count / Convert.ToInt32(Convert.ToString(dr["Акция"]).Substring(0, Convert.ToString(dr["Акция"]).IndexOf('+')))) * Convert.ToInt32(Convert.ToString(dr["Акция"]).Substring(0, Convert.ToString(dr["Акция"]).IndexOf('+')));
                            else odc[i].count = -1;
                        }
                    }
                }
                foreach (OwnerDrugsCount o in odc)
                {
                    if (o.count > 0 || o.count == -1)
                    {
                        OwnerDrugsCount[] odc_buf = new OwnerDrugsCount[] {};
                        foreach (DataRow dr in need.Rows)
                        {
                            if (o.owner == Convert.ToString(dr["Юр лицо"]) && o.drugcode == Convert.ToInt32(dr["Код товара"]) && Convert.ToBoolean(dr["Флаг"]))
                            {
                                Array.Resize(ref odc_buf, odc_buf.Length + 1);
                                odc_buf[odc_buf.Length - 1].drugcode = o.drugcode;
                                odc_buf[odc_buf.Length - 1].owner = o.owner;
                                odc_buf[odc_buf.Length - 1].order = Convert.ToInt32(dr["Потребность"]);
                                odc_buf[odc_buf.Length - 1].pharm = Convert.ToInt32(dr["Код аптеки"]);
                                odc_buf[odc_buf.Length - 1].pharmname = Convert.ToString(dr["Аптека"]);
                                odc_buf[odc_buf.Length - 1].drugname = Convert.ToString(dr["Товар"]);
                            }
                        }

                        for (int i = 0; i < odc_buf.Length; i++)
                        {
                            OwnerDrugsCount max = odc_buf[i];
                            for (int j = i; j < odc_buf.Length; j++)
                            {
                                if (odc_buf[j].order > max.order)
                                {
                                    odc_buf[i] = odc_buf[j];
                                    odc_buf[j] = max;
                                    max = odc_buf[i];
                                }
                            }
                        }
                        int fl = o.count;
                        while (fl > 0)
                        {
                            for (int i = 0; i < odc_buf.Length; i++)
                            {
                                if (odc_buf[i].order > 0 && fl > 0)
                                {
                                    odc_buf[i].order--;
                                    fl--;
                                }
                            }
                        }
                        foreach(OwnerDrugsCount od in odc_buf)
                        {
                            Array.Resize(ref odc_new, odc_new.Length + 1);
                            odc_new[odc_new.Length - 1] = od;
                        }
                    }  
                }
                float sum = 0;
                float bonus = 0;
                foreach (OwnerDrugsCount o in odc_new)
                {
                    if (o.order > 0)
                    {
                        foreach (DataRow dr in anprice.Rows)
                        {
                            if (Convert.ToInt32(dr["Код товара"]) == o.drugcode)
                            {
                                object[] obj = { o.drugcode, Convert.ToString(dr["Код от поставщика"]), o.drugname, o.pharmname, o.owner, o.order, Convert.ToSingle(dr["Цена"]), Convert.ToSingle(dr["Цена"]) * o.order, Convert.ToSingle(dr["Цена"]) * o.order * Convert.ToSingle(dr["Кредит-нота"]) };
                                order.Rows.Add(obj);
                                sum += Convert.ToSingle(dr["Цена"]) * o.order;
                                bonus += Convert.ToSingle(dr["Цена"]) * o.order * Convert.ToSingle(dr["Кредит-нота"]);
                            }
                        }
                    }
                }
                if (order.Rows.Count > 0)
                {
                    object[] obj = { null, null, "Итого", null, null, null, null, sum, bonus };
                    order.Rows.Add(obj);
                }
            }
        }

        private bool CheckParam(object sender, EventArgs e)
        {
            if (city.Rows.Count == 0)
            {
                MessageBox.Show("Выберите города");
                button3_Click(sender, e);
            }

            while (SearchFl(city) == 0)
            {
                MessageBox.Show("Выберите города");
                button3_Click(sender, e);
            }

            if (suppl.Rows.Count == 0)
            {
                MessageBox.Show("Выберите города");
                button4_Click_1(sender, e);
            }

            while (SearchFl(suppl) == 0)
            {
                MessageBox.Show("Выберите города");
                button4_Click_1(sender, e);
            }

            while (SearchFl(suppl) > 1)
            {
                MessageBox.Show("Выберите только одного поставщика");
                button4_Click_1(sender, e);
            }

            return true;
        }
        private int SearchFl(DataTable dt)
        {
            int fl = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (Convert.ToBoolean(dr["Флаг"])) fl++;
            }
            return fl;
        }

        private DataTable AddColumn(DataTable dt, String name, Type type, bool read)
        {
            DataColumn dc = dt.Columns.Add(name, type);
            dc.ReadOnly = read;
            dt.Columns["Флаг"].SetOrdinal(0);
            return dt;
        }

        private void DragDropDGV1()
        {
            int num = 0;
            for (int i = 0; i < begdata.Columns.Count; i++)
            {
                if (i > 5)
                {
                    begdata.Columns.Remove(begdata.Columns[i]);
                }
                else
                {
                    if (begdata.Columns[i].ColumnName != "Флаг")
                    {
                        if (num == 0) begdata.Columns[i].ColumnName = "Код от поставщика";
                        if (num == 1) begdata.Columns[i].ColumnName = "Акция";
                        if (num == 2) begdata.Columns[i].ColumnName = "Цена";
                        if (num == 3) begdata.Columns[i].ColumnName = "Кредит-нота";
                        num++;
                    }
                }
            }
            if (begdata.Columns.Count == 1) begdata = AddColumn(begdata, "Код от поставщика", typeof(String), true);
            if (begdata.Columns.Count == 2) begdata = AddColumn(begdata, "Акция", typeof(String), true);
            if (begdata.Columns.Count == 3) begdata = AddColumn(begdata, "Цена", typeof(Single), true);
            if (begdata.Columns.Count == 4) begdata = AddColumn(begdata, "Кредит-нота", typeof(Single), true);
            begdata.Columns["Флаг"].SetOrdinal(0);

            dataGridView1.DataSource = begdata.DefaultView;
        }

        private void CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            tabControl1.Invoke((Func<int>)(() => tabControl1.SelectedIndex = 1));
            this.Invoke((Func<string>)(() => this.Text = formtext));
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            panel2.Invoke((Func<bool>)(() => panel2.Enabled = true));
            tabControl1.Invoke((Func<bool>)(() => tabControl1.Enabled = true));
            dataGridView2.Invoke((Func<object>) (() => dataGridView2.DataSource = anprice.DefaultView));
        }

        private void CallBackFuncNeed(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            tabControl1.Invoke((Func<int>)(() => tabControl1.SelectedIndex = 2));
            this.Invoke((Func<string>)(() => this.Text = formtext));
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            panel2.Invoke((Func<bool>)(() => panel2.Enabled = true));
            tabControl1.Invoke((Func<bool>)(() => tabControl1.Enabled = true));
            dataGridView3.Invoke((Func<object>)(() => dataGridView3.DataSource = need.DefaultView));
        }

        private void CallBackFuncOrder(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            tabControl1.Invoke((Func<int>)(() => tabControl1.SelectedIndex = 3));
            this.Invoke((Func<string>)(() => this.Text = formtext));
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            panel2.Invoke((Func<bool>)(() => panel2.Enabled = true));
            tabControl1.Invoke((Func<bool>)(() => tabControl1.Enabled = true));
            dataGridView4.Invoke((Func<object>)(() => dataGridView4.DataSource = order.DefaultView));
        }

        private DataTable AnPriceAddCol(DataTable result,DataTable donor)
        {
            string column = "";
            int i = 0;
            foreach (DataColumn c1 in result.Columns)
            {
                foreach (DataColumn c2 in donor.Columns)
                {
                    if (c1.ColumnName == c2.ColumnName)
                    {
                        column = c1.ColumnName;
                        i++;
                    }
                }
            }

            if (i == 0)
            {
                MessageBox.Show("Нет столбца для привязки");
                return null;
            }
            if (i > 1)
            {
                MessageBox.Show("Больше одного столбца для привязки");
                return null;
            }

            foreach (DataColumn c1 in donor.Columns)
            {
                if (c1.ColumnName != column)
                {
                    result.Columns.Add(c1.ColumnName, c1.DataType);
                    foreach (DataRow r1 in donor.Rows)
                    {
                        foreach (DataRow r2 in result.Rows)
                        {
                            if(r1[column].ToString() == r2[column].ToString())
                            {
                                r2[c1.ColumnName] = r1[c1.ColumnName];
                            }
                        }
                    }
                }
            }

            return result;
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '.') e.KeyChar = ',';
            if (!(Char.IsDigit(e.KeyChar)) && !((e.KeyChar == ',') && (textBox2.Text.IndexOf(",") == -1) && (textBox2.Text.Length != 0)) && !((e.KeyChar == '-') && (textBox2.Text.IndexOf("-") == -1)))
            {
                if (e.KeyChar != (char)Keys.Back)
                {
                    e.Handled = true;
                }
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsDigit(e.KeyChar)))
            {
                if (e.KeyChar != (char)Keys.Back)
                {
                    e.Handled = true;
                }
            }
        }

        private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (dataGridView1.RowCount > 0)
            {
                if (Convert.ToBoolean(dataGridView1["Флаг", e.RowIndex].Value))
                    dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
                else
                    dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
            }
        }

        private void dataGridView2_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (dataGridView2.RowCount > 0)
            {
                if (Convert.ToBoolean(dataGridView2["Флаг", e.RowIndex].Value))
                    dataGridView2.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
                else 
                    dataGridView2.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;

            }
        }

        private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if(Convert.ToBoolean(dataGridView2["Флаг",e.RowIndex].Value))
                dataGridView2.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
            else 
                dataGridView2.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (Convert.ToBoolean(dataGridView1["Флаг", e.RowIndex].Value))
                dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
            else
                dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGridView3_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (dataGridView3.RowCount > 0)
            {
                if (Convert.ToBoolean(dataGridView3["Флаг", e.RowIndex].Value))
                    dataGridView3.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
                else
                    dataGridView3.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
            }
        }

        private void dataGridView3_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (Convert.ToBoolean(dataGridView3["Флаг", e.RowIndex].Value))
                dataGridView3.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
            else
                dataGridView3.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
        }




        

    }

}
